<template>
    <div class="inspection-system">
      <!-- Header -->
      <div class="header">
        <div class="header_left">
            <div class="logoContainer">
                <img class="logo" src="../assets//image//logo.png" alt="logo">
            </div>
            <div class="title">铁运无人机智能巡检系统</div>
        </div>
        <div class="user-info">
            <img class="time_img" src="../assets/image/time.png" alt="">
            <div>
                <div class="time">{{currentTimeYMW }}</div>
                <div class="timeHM">{{currentTimeHM }}</div>
            </div>
                <div class="user">ruiboer</div>

                <!-- 这里是退出登录页相关逻辑 -->
                  <el-button type="warning" @click="confirmEvent">退出登录</el-button>
        </div>
      </div>
      <!-- 分割线 -->
      <hr class="line">

  <div class="toolbar">
    <div class="left-section">
      <div style="width: 5px;height: 1rem;background-color: skyblue;"></div>
      <span style="font-size: 1rem;margin-left: 0.6rem;line-height: 100%;">巡检记录</span>
    </div>
    <div class="right-section">
        <span style="font-size: 0.8rem;">图片格式:PNG/JPG/JPEG/BMP单次最多选择10张图片</span>
      <button class="create-task-btn" @click="showUpLoad">创建任务</button>
    </div>
  </div>

      <!-- 分割线 -->
      <hr class="line1">
      <!-- 下方主要部分展示 -->
      <div class="main-content">
        <!-- 左侧区域 -->
        <div class="content_left">
          <div class="demo-time-range">
          <el-input
            v-model="startTime"
            style="width: 48%"
            placeholder="开始时间"
            :prefix-icon="Timer"
          />
          <el-input
            v-model="endTime"
            style="width: 48%"
            placeholder="结束时间"
            :prefix-icon="Timer"
          />
        </div>
          <!-- 一共多少条数据 -->
          <span>共有</span><span style="color: skyblue;">{{data.length}}</span><span>条数据</span>
          <!-- 这里展示表格 -->
          <div  class="table-container">
    <table>
      <thead>
        <tr>
          <th>序号</th>
          <th>巡检时间</th>
          <th>铁路名称</th>
          <th>结果</th>
          <th></th>
        </tr>
      </thead>
      <tbody>
        <tr  v-for="(item) in filteredDataWithIndex"
        :key="item.id"
        :class="{ selectedRow: selectedId === item.id }"
        @click="selectRow(item.id,item)" >
          <td>{{ item.index}}</td>
          <td>{{ item.createTime }}</td>
          <td>{{ item.railName }}</td>
          <td v-if="item.abnormalNumber == 0 && item.normalNumber == 0">{{ '解析中...' }}</td>
          <td v-else>
             <span :style="{color: item.abnormalNumber === 0 ? 'green' : 'red', fontSize: '0.7rem' }">
                {{ item.abnormalNumber }}
                </span>
                /
              <span style="font-size: 0.7rem;">
                {{ item.totalNumber }}
            </span>
          </td>


          
          <td>
            <el-popconfirm
                    confirm-button-text="确认"
                    cancel-button-text="取消"
                    :icon="InfoFilled"
                    icon-color="#626AEF"
                    title="确认删除该条巡检记录吗?"
                    @confirm="deleteItem(item.id)"
                    @cancel="cancelEvent"
                  >
                  <template #reference>
                    <el-icon><Delete /></el-icon>
                    </template>
                </el-popconfirm>
          </td>
        </tr>
      </tbody>
    </table>
  </div>
  <div  v-show="data.length !== 0"  class="demo-pagination-block">
    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :size="size"
      :disabled="disabled"
      :background="background"
      layout="prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
  <div class="rersultcontainer">
    缺陷统计
  </div>
  <div id="chart-container" style="width:100%;height: 15rem;"></div>
        </div>

        <!-- 中间区域 -->
        <div class="content_middle" >
          <div class="rersultcontainer_one">
            结果预览
          </div>
          <!-- 这里是下拉框 -->
          <div class="selectContainer">
            <el-select
            v-model="selectValue"
            placeholder="全部"
            size="small"
            style="width: 9rem"
          >
            <el-option
              v-for="item in selectOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          </div>
          <!-- 现在这里展示相关的加载详情 -->
          <div class="main_result_container" v-if="defaultImg">
            <!-- 这个是每一项 -->
            <div
            v-for=" in filteredData2" 
            >
            <div class="liem_container" style="height: 7rem;color: white;background-color: rgba(100,200,200,0.4);position: relative;">
              <el-icon size="28" style="position: absolute;top: 45%;left: 50%;transform: translate(-50%,-50%);"><Loading /></el-icon>
              <div style="position: absolute;top: 70%;left: 50%;transform: translate(-50%,-50%);">图片上传中</div>
            </div>
          </div>

          </div>


          <div class="main_result_container" v-else>
            <!-- 这个是每一项 -->
            <div
            v-for="item in paginatedData1" :key="item.id"
            >
            <div class="liem_container"    :class=" {'selected-border': selectedImageId === item.id } "  @click="showLargeImage(item.imageUrl,item.id,item)">
                <!-- 左边部分，占比50% -->
                <div class="liem_container_left"  style="background:  rgb(74, 158, 255) ;position: relative;"    v-if=" item.status === '2' ">
                  <!-- 动态绑定颜色 -->
                  <div style="position: absolute;top: 50%;transform: translateY(-50%);"  class="item_status">
                      努力解析中...
                  </div>
                </div>


                <div class="liem_container_left"  v-else >
                  <!-- 动态绑定颜色 -->
                  <div :style="{ background: item.status === '0' ? 'linear-gradient(to right, rgb(74, 255, 144), transparent)' : item.status === '1' ? 'linear-gradient(to right, rgb(255, 74, 74), transparent)' : 'linear-gradient(to right, rgb(74, 158, 255), transparent)' }" class="item_status">{{
                      item.status === '0' ? '正常' : item.status === '1' ? '缺陷' : '解析中...'
                  }}</div>
                  <!-- 修改成for循环 -->
                  <div class="item_message_boder">
                    <div>
                      <!-- 动态生成的选项列表 -->
                      <div v-if="item.status != '2'" class="options-container1">
                            <div
                               v-for="(items, index) in JSON.parse(item.result).results"
                                :key="index"
                                  class="option-item1"
                                    >
                                  <div class="message_item1">
                                    <div class="status-dot" :style="{ backgroundColor: items.flag == 0 ? 'green' : 'red' }"
                                      ></div>
                                       <div style="font-size: 0.6rem; color: white;margin: 2px 0px;">
                                         {{ items.model === 'hudiekou' ? '蝴蝶扣异常' : items.model === 'yilaguan' ? '轨道异物' : items.model === 'person' ? '行人入侵' : items.model === 'custom1' ? '轨道间隙' : items.model === 'custom2' ? '鸟巢异物' : items.model === 'custom3' ? '息闭箱破损' : '其他异常'  }}
                                            </div>
                                          </div>
                                  </div>                            
                                            </div>

                      <div v-else  class="option">
                        <!-- 循环的内容 -->
                        <div class="message_item">
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
                <!-- 右边边部分，占比50% -->
                <div class="liem_container_right">
                  <img 
                  class="right_image"
                  :src="item.imageUrl" alt="" 
                 ></img>
                </div>

            </div>
          </div>

          </div>

          <!-- 分页选项 -->
          <div style="margin-top:1rem;">
            <el-pagination
            v-model:current-page="currentPage1"
            :page-size="pageSize1"
            :size="size"
            :disabled="disabled"
            :background="background"
            layout="prev, pager, next"
            :total="total1"
            @size-change="handleSizeChange1"
            @current-change="handleCurrentChange1"
            />
          </div>
        </div>
        <!-- 右边区域 -->
          <div   class="content_right">
          <div class="rersultcontainer_one">
            结果详情
          </div>
          <!-- 大图片 -->
          




          <div class="container_right_image" style="background-color: rgba(10, 10, 10, 0.3);" v-if="defaultImg">
                <!-- 原图显示 -->
                <el-empty :image-size="200" />
          </div>
          <div class="container_right_image" v-else>
                <!-- 原图显示 -->
          <img 
              :src="largeImageUrl" 
              alt="Selected Image" 
              style="width: 100%; height: 100%; object-fit: contain;"
              @click="enterFullscreen()"
          />
          </div>


          <!-- 结果详情 -->
          <div v-if="selectImageMessage && selectImageMessage.result" class="result_text"  :style="{ background:itemFlag === 0 ? 'linear-gradient(to right, rgb(74, 255, 144), transparent)' : itemFlag === 1 ? 'linear-gradient(to right, rgb(255, 74, 74), transparent)' : 'linear-gradient(to right, rgb(255, 74, 74), transparent)'}"
          >
          {{itemFlag === 0 ? '目前情况一切正常':'存在异常情况，请注意'}}
          </div>

          <div v-else class="result_text" style="background:linear-gradient(to right, rgb(74, 158, 255), transparent)"
          >
             {{defaultImg === true ? "图片上传中，请稍候" : "解析中..."}}
          </div>
          <!-- 循环查看有问题的选项 -->

          <div class="option-container">
  <div
    v-if="selectImageMessage && selectImageMessage.result"
    v-for="(item, index) in JSON.parse(selectImageMessage.result).results"
    :key="index"
    class="option-item"
    :class="{ selected: selectedOptionIndex === index }"
    :style="{
      backgroundColor: item.flag === 0 ? 'green' : 'red',
    }"
    @click="selectOption(index, item)"
  >
    <div class="option-title">
      {{ item.model === 'hudiekou' ? '蝴蝶扣异常' : item.model === 'yilaguan' ? '轨道异物' : item.model === 'person' ? '行人入侵' : item.model === 'custom1' ? '轨道间隙' : item.model === 'custom2' ? '鸟巢异物' : item.model === 'custom3' ? '息闭箱破损' : '其他异常' }}
    </div>
  </div>
</div>


        </div>
      </div>
    </div>
    <!-- 新建的右侧抽屉 -->
    <el-drawer
    v-model="dialog"
    title="铁路巡检新建"
    :before-close="handleClose"
    direction="ltr"
    class="demo-drawer"
  >
    <div class="demo-drawer__content">
      <div style="margin: 2rem  0" ></div>
      <div>请输入铁路的名称</div>
      <div style="margin: 2rem  0" ></div>
      <el-input
        v-model="railName"
        style="width: 100%"
        autosize
        type="textarea"
        placeholder="请输入铁路的名称"
      />
      <div style="margin: 2rem  0" ></div>
      <div>请上传需要检测的图片</div>
      <div style="margin: 2rem  0" ></div>
      <el-upload
        v-model:file-list="fileList"
        action=""
        :auto-upload="false"
        list-type="picture-card"
        :on-preview="handlePictureCardPreview"
        :on-remove="handleRemove"
        multiple 
        accept="image/*" 
      >
        <el-icon><Plus /></el-icon>
      </el-upload>

      <el-dialog v-model="dialogVisible">
        <img w-full :src="dialogImageUrl" alt="Preview Image" />
      </el-dialog>
      <div style="margin: 2rem  0" ></div>
      <div class="demo-drawer__footer">
        <el-button @click="cancelForm">取消</el-button>
        <el-button type="primary" :loading="loading" @click="onClick">
          {{ loading ? '提交中 ...' : '提交' }}
        </el-button>
      </div>
    </div>
  </el-drawer>

  </template>

  
  <script lang="ts" setup>
  import { useRouter } from 'vue-router'
  import { ref, onMounted , computed , watch} from 'vue';
  import { Timer ,Plus ,InfoFilled, Delete,Loading} from '@element-plus/icons-vue'
  import type { ComponentSize } from 'element-plus'
  import * as echarts from 'echarts';
  import { EChartsOption } from 'echarts';
  import type { UploadProps, UploadUserFile } from 'element-plus';
  import request from '../utils/request'


// 定义接口
  interface RailRecord {
  id: number
  railName: string
  abnormalNumber:number
  createTime:string
  normalNumber:number
  totalNumber:number
  }

  interface RailResult {
    id:number
    imageUrl: string
    recordID: number
    result: string
    status: string
  }

  // 退出登录相关逻辑
  // 确认回到登录页面
  const filteredData2 = [{},{},{},{}]
  const router = useRouter()
  const confirmEvent = () => {
    localStorage.removeItem('isLoggedIn');
    localStorage.removeItem('username');
    localStorage.removeItem('password');
  router.go(-1)
}
// 取消
const cancelEvent = () => {
}

// 左侧巡检记录点击删除按钮
 const deleteItem = (id:number) => {
    request.get('/deleteRailRecordByID', {
         params: {
            recordID: id // 将 recordID 替换为实际的参数值
    }
  }).then(
    res => {
      data.value  = res.data
      // 再次获取全部信息
      fetchData()
      
    }
  )
 };

//进入页面调用接口获取巡检的相关数据
  const data =ref<RailRecord[]>([])
    const resultData =ref<RailResult[]>([])
  // const pollingInterval = 1000 // 每秒轮询一次
// 调用接口，获取相关的data数据
const abnormalTotle = ref<any>(100)
      const abnormalHudiekou = ref<number>(20)
      const abnormalPerson = ref<any>(30)
      const abnormalYilaguan = ref<any>(50)
const  selectedId = ref<number | null>(null);
  const fetchData = () => {
    request.get('/getAllRailRecord').then(response => {
      
    data.value  = response.data
      if (filteredData.value.length > 0) {
            selectedId.value = filteredData.value[0].id; 
            abnormalHudiekou.value = filteredData.value[0].abnormalHudiekou; 
            abnormalPerson.value = filteredData.value[0].abnormalPerson; 
            abnormalYilaguan.value = filteredData.value[0].abnormalYilaguan; 
            abnormalTotle.value = filteredData.value[0].abnormalHudiekou + filteredData.value[0].abnormalPerson + filteredData.value[0].abnormalYilaguan;
        // 更新饼状图
        updatePieChart();
            
            if (selectedId.value !== null) {
                fetchDataResult(selectedId.value);
            }
        }
    
    }).catch(error => {
    console.error(error)
    })
  }
    // 右侧抽屉相关的逻辑
const dialog = ref(false)
const loading = ref(false) 


const handleClose = () => {
  loading.value = false
  dialog.value = false
}

const cancelForm = () => {
  loading.value = false
  dialog.value = false
}
// 上传图片相关
const fileList = ref<UploadUserFile[]>([])
const railName = ref<any>('淮河能源铁路')

const dialogImageUrl = ref('')
const dialogVisible = ref(false)

// 删除逻辑
const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles)
}
// 预览逻辑
const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
}

const showUpLoad = () => {
  dialog.value = true;
   fileList.value = []
}
// 上传逻辑
const defaultImg = ref(false)
const onClick = async () => {
  selectedOptionIndex.value = null;
  loading.value = true;
 
    loading.value = false;
    dialog.value = false;
    const formData = new FormData();

    // 检查 fileList 是否为空
    if (fileList.value.length === 0) {
      console.error("No files selected.");
      return;
    }
    // 将铁路名称放到FormData里面
    if(railName){
     formData.append("railName",railName.value)
    }else {
        console.error("error:", railName);
      }

    // 将每个文件添加到 FormData
    fileList.value.forEach(file => {
      // 使用类型断言，确保 file.raw 是 Blob 类型
      const rawFile = file.raw as Blob;  // 类型断言
      if (rawFile) {
        formData.append("inputFiles", rawFile);
      } else {
        console.error("File is missing raw property:", file);
      }
    });

    try {
      const responseOne = await request.post("/insertRailRecord", formData, {
        headers: {
          "Content-Type": "multipart/form-data",
        },
      });
      if(responseOne.data.status === 'success'){
        console.log(111);
        selsetImageUrl.value = ''
        defaultImg.value = true
        fetchData()
      }

      const responseResult = await request.post("/uploadResult", formData, {
        headers: {
          "Content-Type": "multipart/form-data",
        },
      });
      if(responseResult.data.status == 'success'){
       loaddingImg.value = true  //意思是加载中，图片上传呢
       defaultImg.value = false
       console.log(222);
       selsetImageUrl.value = ''
       fetchData()
      }
      
      

      // 使用 await 确保请求完成后再继续
      const response = await request.post("/insertRailway", formData, {
        headers: {
          "Content-Type": "multipart/form-data",
        },
      });
      console.log("Upload successful:", response.data);
      console.log(333);
      
      selsetImageUrl.value = ''
      const urls = response.data.resultMessage
        .flatMap((item:any) => 
         item.results.map((result:any) => result.imageUrl).filter((url:any) => url !== null)
      );

      // 现在使用预加载
      urls.forEach((url:any)=>{
        const img = new Image()
        img.src = url; 

        // 处理图片加载成功
        img.onload = () => {
        console.log(`图片加载成功: ${url}`);
  };

        // 处理图片加载失败
         img.onerror = () => {
        console.error(`图片加载失败: ${url}`);
  };
      })
       loaddingImg.value = false  //意思是加载中，图片上传呢

        fetchData()
    } catch (error) {
    }
}     

// 这里是时间筛选相关的操作
    const startTime = ref();  // 开始时间
    const endTime = ref();    // 结束时间

    // 过滤数据的 computed 属性
    
    const filteredData:any = computed(() => {
      if(!startTime || !endTime ) {
        return paginatedData
      }else {
        return paginatedData.value.filter(item => {
        const itemTime = new Date(item.createTime).getTime();
        const start = startTime.value ? new Date(startTime.value).getTime() : null;
        const end = endTime.value ? new Date(endTime.value).getTime() : null;
        return (!start || itemTime >= start) && (!end || itemTime <= end);
      });
      }
    } 
  ); 
  

    // 定义动态序号的逻辑
const filteredDataWithIndex = computed(() => {
  const startIndex = (currentPage.value - 1) * pageSize.value; // 当前页起始索引
  return filteredData.value.map((item:any, index:any) => ({
    ...item,
    index: startIndex + index + 1, // 动态计算序号
  }));
});

  const loaddingImg =  ref(false)
  const selectRow = (id: number,item:any) => {
    // 最左侧点击的时候清空一下
    console.log(444);
    
     selsetImageUrl.value = ''
      if(item.normalNumber + item.abnormalNumber == item.totalNumber) {
        defaultImg.value = false
      }else  if(loaddingImg.value){
        defaultImg.value = false
      }else {
        defaultImg.value = true
      }
      selectedOptionIndex.value = null;
      abnormalHudiekou.value = item.abnormalHudiekou
      abnormalPerson.value = item.abnormalPerson
      abnormalYilaguan.value = item.abnormalYilaguan
      abnormalTotle.value =  item.abnormalHudiekou + item.abnormalPerson + item.abnormalYilaguan             
      // 更新一下饼状图
      updatePieChart();
      selectedId.value = id;

    // 获取中间部分数据
    fetchDataResult(id);

    // 确保中间部分的第一条被默认选中
    setTimeout(() => {
        const newData = filteredData1.value;
        if (newData.length > 0) {
            // 默认选中中间部分的第一条
            largeImageUrl.value = newData[0].imageUrl; // 更新右侧大图片
            selectedImageId.value = newData[0].id; // 更新选中状态
            selectImageMessage.value = newData[0]; // 更新详细信息
            showLargeImage(newData[0].imageUrl,newData[0].id,newData[0])   
            console.log(3333333333,newData[0]);
                   
        } else {
            // 如果没有数据，清空右侧显示
            largeImageUrl.value = undefined;
            selectedImageId.value = null;
            selectImageMessage.value = null;
        }
    }, 0); // 延迟以确保 `filteredData1` 更新完成
};




    // 这里是下拉框相关的数据
    const selectValue = ref('01')

      const selectOptions = [
        {
          value: '01',
          label: '全部',
        },
        {
          value: '02',
          label: '正常',
        },
        {
          value: '03',
          label: '缺陷',
        },
]

  // 过滤数据的 computed 属性
    
// 初始化大图片 URL 的响应式变量

const largeImageUrl = ref<string | undefined>(undefined);

  const selectedImageId = ref<number | null>(null); // 用于存储当前选中的图片 ID
  const itemFlag = ref();

  // 存储item的信息，也就是接口返回的相关信息
  const selectImageMessage = ref<any>(null);//用于存储当前item返回的相关信息
// 点击小图片时，展示右侧大图片
  const selsetImageUrl = ref<any>(null); //用于存储原图相关信息
const showLargeImage = (imageUrl: string ,id: number,item:any) => {
    console.log('让我看看这个imageUrl是什么',imageUrl,item);
    // 将imageUrl存储下来
    selectedOptionIndex.value = null;
    largeImageUrl.value = imageUrl;   
    selsetImageUrl.value = imageUrl 
    selectedImageId.value = id; // 更新当前选中的图片 ID
    selectImageMessage.value = item;
    itemFlag.value = JSON.parse(selectImageMessage.value.result).flag
    
};

const selectedOptionIndex = ref<number | null>(null);

// 更新选中状态的方法
const selectOption = (index: number, item: any) => {
  selectedOptionIndex.value = index; // 更新选中的索引  
 if(item.image_url){
  // 修改图片
  largeImageUrl.value = item.image_url
  console.log('异常情况下',largeImageUrl.value);
  
 }else{
  // 显示原图
  console.log('正常，正常',selsetImageUrl.value);
  
  largeImageUrl.value = selsetImageUrl.value
 }
};




    // 图片或者canvas放大的逻辑
    const enterFullscreen = () => {
    const container = document.querySelector(".container_right_image") as HTMLElement;

    if (container.requestFullscreen) {
        container.requestFullscreen().then(() => {
        }).catch((err) => {
            console.error("全屏失败:", err);
        });
    } else {
        console.error("当前浏览器不支持全屏 API");
    }
};


// 确保 filteredData1 中默认展示第一条的图片
const filteredData1 = computed(() => {
    let filtered = resultData.value || [];  // 确保 resultData 是一个数组

    // 按选择项过滤数据
    if (selectValue.value === '02') {
        filtered = filtered.filter(item => item.status === '0');
    } else if (selectValue.value === '03') {
        filtered = filtered.filter(item => item.status === '1');
    }
    if (filtered.length > 0 && selectedImageId.value === filtered[0].id) {
        largeImageUrl.value = filtered[0].imageUrl;  // 更新右侧大图片 URL
        selectedImageId.value = filtered[0].id;  // 默认选中第一张图片
        selectImageMessage.value = filtered[0];  // 更新图片的详细信息
        showLargeImage(filtered[0].imageUrl, filtered[0].id, filtered[0])  // 显示大图
    }

    return filtered;
});


    // 这里是中间部分相关的分页
    const fetchDataResult = (id: number) => {
      // 先将上面的那部分数据清空
      console.log(555);
      
      // selsetImageUrl.value = ''
      resultData.value = []
    request.get('/getRailResultByRecordID', {
        params: { recordID: id }
    })
    .then(response => {
        resultData.value = response.data;
        // 如果中间部分有数据，默认选中第一条
        if (filteredData1.value.length > 0) {
            largeImageUrl.value = filteredData1.value[0].imageUrl;
            selectedImageId.value = filteredData1.value[0].id;
            selectImageMessage.value = filteredData1.value[0];
            itemFlag.value = JSON.parse(selectImageMessage.value.result).flag
            showLargeImage(filteredData1.value[0].imageUrl,filteredData1.value[0].id,filteredData1.value[0])            
    } else {
      // 如果没有数据，清空右侧显示
      largeImageUrl.value = undefined;
      selectedImageId.value = null;
      selectImageMessage.value = null;
    }
    })
    .catch(error => {
        console.error(error);
    });
};

      
    const total1 = computed(() => (filteredData1.value ? filteredData1.value.length : 0));
    const currentPage1   = ref(1)
    // 每页显示数据数量
    const pageSize1 = ref(4)

  // 计算当前页需要显示的数据
  const paginatedData1 = computed(() => {    
    // selsetImageUrl.value = ''
    // 基于过滤后的数据进行分页
    const start = (currentPage1.value - 1) * pageSize1.value;
    const end = start + pageSize1.value;
    return filteredData1.value.slice(start, end);  // 使用筛选后的数据进行分页
    });

    // 更新分页大小
    const handleCurrentChange1 = (newPage: number) => {
      // selsetImageUrl.value = ''
    currentPage1.value = newPage;
    selectedOptionIndex.value = null;

    // 更新右侧默认图片为当前页的第一张
    const newPageData = paginatedData1.value;
    if (newPageData.length > 0) {
      // selsetImageUrl.value = ''
        largeImageUrl.value = newPageData[0].imageUrl;
        selectedImageId.value = newPageData[0].id;
        selectImageMessage.value = newPageData[0];
        showLargeImage(newPageData[0].imageUrl,newPageData[0].id,newPageData[0])

    }
};

const handleSizeChange1 = (newSize: number) => {
    // selsetImageUrl.value = ''
    pageSize1.value = newSize;
    selectedOptionIndex.value = null;


    // 更新右侧默认图片为当前页的第一张
    const newPageData = paginatedData1.value;
    if (newPageData.length > 0) {
        // selsetImageUrl.value = ''
        largeImageUrl.value = newPageData[0].imageUrl;
        selectedImageId.value = newPageData[0].id;
        selectImageMessage.value = newPageData[0];
        showLargeImage(newPageData[0].imageUrl,newPageData[0].id,newPageData[0])
    }
};
    // 表格相关数据以及函数

  
  // 定义一个响应式变量来存储当前时间
  const currentTimeYMW = ref<string>('');
    const currentTimeHM = ref<string>('');
    // 分页相关的数据
    const size = ref<ComponentSize>('default')
    const background = ref(true)
    const disabled = ref(false)
    const total = computed(() => (data.value ? data.value.length : 0))
    // 当前的页数
    const currentPage = ref(1)
    // 每页显示数据数量
    const pageSize = ref(10)

  // 计算当前页需要显示的数据
  const paginatedData = computed(() => {
    
    if (!data.value) return [] 
      const start = (currentPage.value - 1) * pageSize.value;
      const end = start + pageSize.value;
      return data.value.slice(start, end);
    });

    // 更新分页大小
    const handleSizeChange = (newSize: number) => {
      pageSize.value = newSize;
      // 分页之后会出现问题
      
    };

    // 更新当前页
    const handleCurrentChange = (newPage: number) => {
      currentPage.value = newPage;
      // 分页之后会出现问题

    };
  
  // 定义一个更新时间的函数
  const updateTime = () => {
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    const hours = String(now.getHours()).padStart(2, '0');
    const minutes = String(now.getMinutes()).padStart(2, '0');
    const seconds = String(now.getSeconds()).padStart(2, '0');
    const weekDays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
    const weekDay = weekDays[now.getDay()];
  
    // 格式化为 YYYY/MM/DD 星期X HH:MM:SS
    currentTimeYMW.value = year + "/" + month + "/" + day + "/" + weekDay ;
    currentTimeHM.value = hours +':'+ minutes + ":" + seconds 
  };


  // 这边是饼状图相关的代码
  let myChart: any; // ECharts 实例
  const updatePieChart = () => {
    const option: EChartsOption = {
  title: {
    text: `总缺陷数 ${abnormalTotle.value}`,
    left: 'center',
    top: 'center',
    textStyle: {
      color: '#fff',
      fontSize: 12,
      fontWeight: 'bold',
    },
  },
  color: ['#5470c6', '#90cb75','#ee6666'],
  legend: {
    orient: 'horizontal',
    bottom: '0',
    left: 'center',
    data: ['蝴蝶扣损坏', '轨道异物', '人员入侵'],
    textStyle: { color: '#fff' },
    show: window.innerWidth > 2000,
  },
  series: [
    {
      type: 'pie',
      data: [
        { value: abnormalHudiekou.value, name: `蝴蝶扣损坏` },
        { value: abnormalYilaguan.value, name: `轨道异物` },
        { value: abnormalPerson.value, name: `人员入侵` },
        { value: 0, name: `轨道间隙` },
        { value: 0, name: `鸟巢异物` },
        { value: 0, name: `息闭箱破损` },
      ],
      radius: ['40%', '70%'],
      label: {
        show: true,  // 显示标签
        position: 'outside',  // 标签位置：外部
        formatter: '{b}\n{c}', // 格式化标签：换行显示
        color: '#fff', // 设置标签文本颜色为白色
        fontSize: 12, // 设置字体大小
        fontWeight: 'bold', // 设置字体加粗
      },
      labelLine: {
        length: 10,  // 标签线的长度
        length2: 5, // 第二段标签线的长度
      },
    },
  ],
};


  if (myChart) {
    myChart.setOption(option); // 更新图表
  }
};
  
  // 在组件挂载时，开始更新时间
  onMounted(() => {

    fetchData()
    fetchDataResult(1)
     // 初始化右侧大图片
     if (filteredData1.value.length > 0) {
        const firstItem = filteredData1.value[0];
        largeImageUrl.value = firstItem.imageUrl; // 右侧默认显示第一张
        selectedImageId.value = firstItem.id; // 默认选中第一张
        selectImageMessage.value = firstItem; // 更新图片的详细信息
    }
    
    updateTime(); // 初始化时调用一次
    setInterval(updateTime, 1000); // 每隔1秒更新一次时间
    

      // 饼状图相关页面逻辑

      const chartDom = document.getElementById('chart-container') as HTMLElement;
        myChart = echarts.init(chartDom);
        updatePieChart();
        window.addEventListener('resize', () => {
        myChart.resize();
  });

  });


    // 监听，当数据修改后，修改饼状图
    watch(
  [abnormalTotle, abnormalHudiekou, abnormalPerson, abnormalYilaguan],
  () => {
    updatePieChart();
  }
);

  </script>
  
  <style scoped>
  .inspection-system {
    display: flex;
    flex-direction: column;
    height: 100vh;
    width: 100%;
    background-image: url("../assets//image/main_pageBg.jpg");
  }
  .mianPage {
    width: 100%;
    height: 100%;
  }
  
  .header {
    display: flex;
    justify-content: space-between;
    padding: 10px;
    color: white;
    height: 7vh;
  }
  .header_left {
    display: flex;
    width: 100%;
    height: 100%;
    align-items: center; /* 垂直居中 */
  }
  .logoContainer {
    margin-left: 2%;
    height: 100%;
    padding-left: 15px;
    padding-right: 15px;
    /* background-color: white; */
    display: flex;
  }
  .logo {
    margin-top: 5%;
    height: 80%;
    width: auto;

  }
  .title {
    font-size: 1.5rem;
    line-height: 100%;
    margin-left: 0.5rem;
  }
  .user-info {
    display: flex;
    width: 40%;
    height: 100%;
    align-items: center; /* 垂直居中 */
  }
  .time_img {
    width: 2rem;
    height: auto;
    margin-right: 0.5rem;
  }
  .time {
    font-size: 0.7rem;
    margin-left: 0.4rem;
  }
  .timeHM {
    font-size: 1.1rem;
    color: #89ceff;
  }
  .user {
    margin-left: 1.5rem;
    margin-right: 0.5rem;
    font-size: 1.1rem;
  }
  .userImg {
    width: 2rem;
    border-radius: 50%;
    margin-left: 1.2rem;
  }
  .setting {
    margin-left: 0.5rem;
    width:1.4rem;
  }
  .line {
  border: none;
  height: 2px; 
  background-color: #2a7afa;
  width: 92%;
  margin:0 4%;
}


/* main_title部分，创建巡检功能开启 */
.line1 {
  border: none;
  height: 2px; 
  width: 90%;
  margin:0 3%;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 5px;
  color: white; /* 字体颜色 */
  margin: 0 3%;
}

.left-section {
  display: flex;
  flex: 1;
}

.right-section {
  flex: 1;
  text-align: right;
}

.create-task-btn {
  margin-left: 2rem;
  background-color: #1c94ff; /* 按钮的蓝色 */
  border: none;
  color: white;
  padding: 5px 16px;
  cursor: pointer;
  border-radius: 5px;
  font-size: 0.7rem;
}

.create-task-btn:hover {
  background-color: #007bff; /* 按钮悬停时的颜色变化 */
}

  /*最下方主要部分区域的代码  */
  .main-content {
    display: flex;
    flex-grow: 1;
    margin:0 3%;
    display: flex;
  }
  .content_left {
    width: 25%;
    padding: 5px;
    position: relative;
  }
  .content_left span {
    color: #fff;
    font-size: 1rem;
    font-weight: 500;
  }
  .demo-time-range{
    display: flex;
    margin-bottom: 0.2rem;
  }
  .table-container {
    margin-top: 0.2rem;
    width: 100%;
    height: 16rem;
}

table {
  width: 100%;
  border-collapse: collapse;
  background-color: transparent;
}

th,
td {
  padding: 0.24rem  0rem;
  text-align: left;
  font-size: 0.6rem;
  color: #ffffff;
}

th {
  font-weight: bold;
  color: #ffffff;
  font-size: 0.9rem;
}

tbody tr:nth-child(odd) {
  background-color: rgba(255, 255, 255, 0.05);
}

tbody tr:nth-child(even) {
  background-color: rgba(255, 255, 255, 0.1);
}

.demo-pagination-block {
  margin-top: 0.5rem;
}

.rersultcontainer {
  width: 100%;
  height: 1.5rem;
  margin-top:0.3rem;
  padding-left: 1rem;
  background: linear-gradient(to right, skyblue, rgba(106, 251, 84, 0));
  color: #fff;
  line-height: 1.5rem;
  font-size: 0.8rem;
  font-weight: bold;
} 

  .content_middle {
    width: 25%;
    padding: 5px;
    position: relative;

  }
  .rersultcontainer_one {
  width: 100%;
  height: 1.6rem;
  padding-left: 1rem;
  background: linear-gradient(to right, skyblue, rgba(106, 251, 84, 0));
  color: #fff;
  line-height: 1.6rem;
  font-size: 0.8rem;
  font-weight: bold;
} 
.selectContainer {
  position: absolute;
  top: 5px;
  right: 5px;
}
.main_result_container{
  width: 100%;
  margin-top:1rem;
}
.liem_container {
  width: 100%;
  display: flex;
  margin-bottom: 1rem;
}
.liem_container_left {
  width: 50%;
  height: 7rem;
  border: 1px solid rgb(71, 71, 71) ;
  border-top: none;
}
.item_status {
  width: 100%;
  height: 1.5rem;
  line-height: 1.5rem;
  color: #fff;
  font-size: 0.8rem;
  font-weight: bold;
  padding-left: 1rem;

}
.message_item {
  padding: 0.2rem;
  display: flex;
  justify-content: space-around
}
.liem_container_right {
  width: 50%;
  height: 7rem;
}
.right_image {
  width: 100%;
  height: 100%;
}

  .content_right {
    width: 50%;
    padding: 5px;
  }
  .container_right_image {
    margin-top: 1rem;
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%; /* 宽度占满父级 */
    height: 26rem; /* 高度占满父级 */
    position: relative; /* 必要时调整定位 */
}
  .result_text {
    margin-top: 1rem;
    width: 100%;
    height: 4rem;
    color: #fff;
    line-height: 4rem;
    padding-left: 1rem;
  }



  /* 容器样式：三列布局 */
.option-container {
  display: flex;
  margin-top: 1rem;
  gap: 15px; /* 选项间距 */
  justify-content:center;
}
.options-container1 {
  display: flex;
  flex-wrap: wrap; /* 支持换行 */
  gap: 10px; /* 每项之间的间距 */
  margin-left: 0.2rem;
  margin-top: 0.4rem;
}
.option-item1 {
  width: calc(50% - 10px); /* 每行两个，扣除间距 */
  display: flex;
  align-items: center;
}
.message_item1 {
  display: flex;
  align-items: center;
}
.status-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%; /* 圆形 */
  margin-right: 8px; /* 与文字的间距 */
}

/* 单个选项样式 */
.option-item {
  width: calc(12% - 10px); /* 三列布局，减去间距 */
  padding: 20px;
  text-align: center;
  border-radius: 8px;
  font-size: 0.6rem;
  font-weight: bold;
  cursor: pointer;
  color: #ffffff; /* 默认字体颜色 */
  transition: transform 0.2s ease, box-shadow 0.2s ease;
}

/* 鼠标悬停效果 */
.option-item:hover {
  transform: scale(1.05); /* 微缩放效果 */
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
}

/* 选中效果 */
.option-item.selected {
  border: 3px solid #ffffff; /* 选中边框颜色 */
  box-shadow: 0 0 10px rgba(255, 255, 255, 0.8); /* 高亮光晕效果 */
}

.option-container {
  display: flex;
  margin-top: 1rem;
  gap: 15px; /* 选项间距 */
  justify-content: center;
}

.option-item {
  width: calc(12% - 8px);
  padding: 20px;
  text-align: center;
  border-radius: 8px;
  font-size: 0.7rem;
  font-weight: bold;
  cursor: pointer;
  color: #ffffff;
  transition: transform 0.2s ease, box-shadow 0.2s ease;
}

.option-item:hover {
  transform: scale(1.05);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
}

.option-item.selected {
  border: 3px solid rgb(231, 231, 52); /* 选中边框 */
  box-shadow: 0 0 10px rgba(255, 255, 255, 0.8); /* 高亮光晕 */
  transform: scale(1.1); /* 微缩放选中状态 */
}



  
  
/* 尝试修改elemnet组件库中分页功能的组件颜色样式 */
.demo-pagination-block + .demo-pagination-block {
  margin-top: 10px;
}
.demo-pagination-block .demonstration {
  margin-bottom: 16px;
}

/* 选中的行应用绿色渐变背景 */
.selectedRow {
  background: linear-gradient(to right, rgb(231, 231, 52), transparent);
}

.selected-border {
  border: 3px solid rgb(231, 231, 52); /* 选中边框的颜色边框 */
}
table td, table th {
  text-align: center; /* 设置表格单元格水平居中 */
  vertical-align: middle; /* 设置表格单元格垂直居中 */
}
  </style>


  